package com.jvmoutofmemory.octopus.ui;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;

public class TrayFactory {

    public static void createSystemTray(MainOctopusFrame frame) {
        if (!SystemTray.isSupported()) {
            System.out.printf("当前系统不支持系统托盘!");
            return;
        }

        SystemTray tray = SystemTray.getSystemTray();
        Image image = getTrayIcon();
        if (image == null) {
            return;
        }

        PopupMenu popupMenu = createPopupMenu(frame);

        TrayIcon trayIcon = new TrayIcon(image, "Octopus批量打印", popupMenu);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(true);
            }
        });

        try {
            tray.add(trayIcon);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static PopupMenu createPopupMenu(MainOctopusFrame frame) {
        PopupMenu popupMenu = new PopupMenu();
        MenuItem exit = new MenuItem("退出");
        MenuItem showFrame = new MenuItem("主界面");

        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        showFrame.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(true);
            }
        });

        popupMenu.add(showFrame);
        popupMenu.add(exit);

        return popupMenu;
    }

    private static Image getTrayIcon() {
        Image image = null;
        try (InputStream inputStream = TrayFactory.class.getClassLoader().getResourceAsStream("com/jvmoutofmemory/octopus/icon/octopus.png")) {
            image = ImageIO.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.printf("读取图标文件失败!");
        }

        return image;
    }

}
